import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/views/dashboard" as DashboardViews
import "qrc:/qml/components" as Components
import "qrc:/qml/components/dashboard" as DashboardComponents
import "qrc:/qml/styles" as Styles

Page {
    id: dashboardScreen
    title: qsTr("仪表板")

    // 从全局ViewModel获取数据模型
    property var taskListModel: GlobalTaskViewModel ? GlobalTaskViewModel.taskListModel : null
    property var agvListModel: GlobalVehicleViewModel ? GlobalVehicleViewModel.agvListModel : null
    property var alerts: []
    property var kpiData: ({
        throughput: 253,
        vehicleUtilization: 95,
        pendingTasks: GlobalTaskViewModel ? GlobalTaskViewModel.activeTaskCount : 0,
        systemUptime: 99.98
    })

    property var dashboardViewModel: GlobalDashboardViewModel

    background: Rectangle {
        color: Styles.Theme.background
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingNormal

        // Main Content Area
        RowLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: Styles.Theme.spacingNormal

            // Left Side: Real-time Map View
            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                Layout.preferredWidth: 2
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusNormal

                DashboardViews.LiveMapView {
                    id: liveMapView
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingSmall

                    // 将agvListModel传递给地图视图
                    agvListModel: dashboardScreen.agvListModel

                    onAgvClicked: agvId => handleAgvClicked(agvId)
                    onStationClicked: stationId => handleStationClicked(stationId)
                    onMapClicked: position => handleMapClicked(position)
                }
            }

            // Right Side: Alerts and Lists
            ColumnLayout {
                Layout.fillHeight: true
                Layout.fillWidth: true
                Layout.preferredWidth: 1
                spacing: Styles.Theme.spacingNormal

                // Task / Vehicle / System Log Lists
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: Styles.Theme.surface
                    border.color: Styles.Theme.border
                    border.width: 1
                    radius: Styles.Theme.radiusNormal

                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingSmall

                        // Tab Bar
                        RowLayout {
                            Layout.fillWidth: true
                            spacing: Styles.Theme.spacingSmall

                            Repeater {
                                model: [qsTr("任务列表"), qsTr("车辆列表"), qsTr("系统日志")]

                                delegate: Rectangle {
                                    Layout.fillWidth: true
                                    Layout.preferredHeight: 40
                                    color: tabView.currentIndex === index ? Styles.Theme.primary : Styles.Theme.backgroundAlternate
                                    border.color: Styles.Theme.border
                                    border.width: 1
                                    radius: Styles.Theme.radiusSmall

                                    Text {
                                        anchors.centerIn: parent
                                        text: modelData
                                        color: tabView.currentIndex === index ? Styles.Theme.textOnPrimary : Styles.Theme.textSecondary
                                        font.pixelSize: Styles.Theme.fontSizeNormal
                                        font.weight: Font.Medium
                                    }

                                    MouseArea {
                                        anchors.fill: parent
                                        cursorShape: Qt.PointingHandCursor
                                        onClicked: tabView.currentIndex = index
                                    }
                                }
                            }
                        }

                        // Tab Content
                            StackLayout {
                                id: tabView
                                Layout.fillWidth: true
                                Layout.fillHeight: true
                                currentIndex: 0

                            // Tasks Tab
                            ScrollView {
                                clip: true

                                ListView {
                                    model: taskListModel
                                    spacing: Styles.Theme.spacingSmall

                                    delegate: Components.TaskListCard {
                                        width: ListView.view.width
                                        chainId: model.chainId || ""
                                        taskName: model.taskName || ""
                                        agvNumber: model.agvNumber || -1
                                        agvName: model.agvName || ""
                                        status: model.status || "pending"
                                        statusDisplay: model.statusDisplay || ""
                                        currentTaskIndex: model.currentTaskIndex || 0
                                        totalTasks: model.totalTasks || 0
                                        progress: model.progress || 0
                                        createTime: model.createTime || ""
                                        errorMessage: model.errorMessage || ""
                                        currentSubTask: model.currentSubTask || ""
                                        currentSubTaskType: model.currentSubTaskType || ""
                                        targetStation: model.targetStation || ""
                                        currentFloor: model.currentFloor || -1
                                        durationSeconds: model.durationSeconds || 0
                                        isPaused: model.isPaused || false
                                        isFinished: model.isFinished || false

                                        onClicked: handleTaskClicked(model.chainId)
                                    }
                                }
                            }

                            // Vehicles Tab
                            ScrollView {
                                clip: true

                                ListView {
                                    model: agvListModel
                                    spacing: Styles.Theme.spacingSmall

                                    delegate: Components.VehicleListCard {
                                        width: ListView.view.width
                                        agvNumber: model.agvNumber || 0
                                        name: model.name || ""
                                        ipAddress: model.ipAddress || ""
                                        type: model.type || 0
                                        currentStation: model.currentStation || ""
                                        lastStation: model.lastStation || ""
                                        targetStation: model.targetStation || ""
                                        currentMap: model.currentMap || ""
                                        currentJob: model.currentJob || ""
                                        waypointX: model.x || 0
                                        waypointY: model.y || 0
                                        heading: model.heading || 0
                                        confidence: model.confidence || 0
                                        batteryLevel: model.batteryLevel || 0
                                        isOnline: model.isOnline || false
                                        isCharging: model.isCharging || false
                                        isLocked: model.isLocked || false
                                        isBlocked: model.isBlocked || false
                                        mode: model.mode || 0
                                        taskStatus: model.taskStatus || 0
                                        taskType: model.taskType || 0
                                        isControlled: model.isControlled || false
                                        errorMessage: model.errorMessage || ""
                                        unfinishedPath: model.unfinishedPath || []
                                        finishedPath: model.finishedPath || []
                                        pathLength: model.pathLength || 0
                                        isBusy: model.isBusy || false

                                        onClicked: handleAgvClicked(model.agvNumber)
                                    }
                                }
                            }

                            // System Log Tab
                            Item {
                                Layout.fillWidth: true
                                Layout.fillHeight: true

                                DashboardComponents.SystemLogPanel {
                                    anchors.fill: parent
                                    logViewModel: GlobalLogViewModel
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Event Handlers
    function handleAgvClicked(agvId) {
        console.log("AGV clicked:", agvId)
        // 聚焦到 AGV 位置
        liveMapView.focusOnAgv(agvId)
    }

    function handleStationClicked(stationId) {
        console.log("Station clicked:", stationId)
    }

    function handleMapClicked(position) {
        console.log("Map clicked:", position.x, position.y)
    }

    function handleTaskClicked(taskId) {
        console.log("Task clicked:", taskId)
        // 查找任务对应的 AGV 并聚焦
        if (!taskListModel) return

        for (var i = 0; i < taskListModel.rowCount(); i++) {
            var taskData = taskListModel.getTaskData(i)
            if (taskData && taskData.chainId === taskId) {
                var agvNumber = taskData.agvNumber || -1
                if (agvNumber > 0) {
                    // 聚焦到任务对应的 AGV
                    liveMapView.focusOnAgv(agvNumber)
                }
                return
            }
        }
    }

    function handleAlertDetails(alertId) {
        console.log("Alert details:", alertId)
    }

    function handleAlertResolve(alertId) {
        console.log("Alert resolve:", alertId)
    }

    // Helper Functions
    function getLogLevelColor(level) {
        const colors = {
            "error": Styles.Theme.danger,
            "warn": Styles.Theme.warning,
            "info": Styles.Theme.info,
            "debug": Styles.Theme.textSecondary
        }
        return colors[level] || Styles.Theme.textSecondary
    }
}
